#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复MongoDB索引冲突问题
"""

from pymongo import MongoClient, TEXT, ASCENDING, DESCENDING

def fix_indexes():
    """修复索引冲突"""
    print("🔧 修复MongoDB索引冲突...")
    
    try:
        client = MongoClient("mongodb://localhost:27017/")
        db = client['civil_code_db']
        collection = db['civil_code_articles']
        
        # 1. 删除所有现有索引（除了_id索引）
        print("🗑️ 删除所有现有索引...")
        existing_indexes = list(collection.list_indexes())
        
        for index in existing_indexes:
            index_name = index.get('name')
            if index_name and index_name != '_id_':
                try:
                    collection.drop_index(index_name)
                    print(f"   ✅ 删除索引: {index_name}")
                except Exception as e:
                    print(f"   ⚠️ 删除索引失败 {index_name}: {str(e)}")
        
        # 2. 重新创建所有索引
        print("\n🔧 重新创建优化索引...")
        
        # 文本搜索索引
        collection.create_index(
            [
                ("content", "text"),
                ("title", "text"),
                ("explanation", "text"),
                ("keywords", "text")
            ],
            name="civil_code_text_search",
            default_language='none',
            weights={
                "content": 10,
                "keywords": 8,
                "title": 5,
                "explanation": 3
            }
        )
        print("   ✅ 文本搜索索引创建成功")
        
        # 关键词数组索引
        collection.create_index(
            [("keywords", ASCENDING)],
            name="keywords_array_index"
        )
        print("   ✅ 关键词索引创建成功")
        
        # 条文号唯一索引
        collection.create_index(
            [("article_number", ASCENDING)],
            name="article_number_unique",
            unique=True
        )
        print("   ✅ 条文号索引创建成功")
        
        # 章节复合索引
        collection.create_index(
            [
                ("chapter_info.part", ASCENDING),
                ("chapter_info.chapter_number", ASCENDING)
            ],
            name="chapter_compound_index"
        )
        print("   ✅ 章节索引创建成功")
        
        # 时间索引
        collection.create_index(
            [("created_at", DESCENDING)],
            name="created_at_index"
        )
        collection.create_index(
            [("updated_at", DESCENDING)],
            name="updated_at_index"
        )
        print("   ✅ 时间索引创建成功")
        
        # 3. 测试搜索功能
        print("\n🧪 测试搜索功能...")
        test_queries = ['民事主体', '合法权益', '人身关系']
        
        for query in test_queries:
            try:
                results = list(collection.find(
                    {"$text": {"$search": query}},
                    {"article_number": 1, "title": 1, "score": {"$meta": "textScore"}}
                ).sort([("score", {"$meta": "textScore"})]).limit(3))
                
                if results:
                    print(f"   ✅ 搜索 '{query}': 找到 {len(results)} 条相关法条")
                    for result in results[:2]:  # 只显示前2条
                        score = result.get('score', 0)
                        print(f"      - {result['article_number']} (得分: {score:.2f})")
                else:
                    print(f"   ⚠️ 搜索 '{query}': 无结果")
            except Exception as e:
                print(f"   ❌ 搜索 '{query}' 失败: {str(e)}")
        
        # 4. 显示最终索引状态
        print("\n📋 最终索引状态:")
        indexes = list(collection.list_indexes())
        for index in indexes:
            index_name = index.get('name', 'unnamed')
            index_keys = list(index.get('key', {}).keys())
            index_unique = index.get('unique', False)
            unique_flag = " [UNIQUE]" if index_unique else ""
            print(f"   - {index_name}: {', '.join(index_keys)}{unique_flag}")
        
        client.close()
        return True
        
    except Exception as e:
        print(f"❌ 索引修复失败: {str(e)}")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("🔧 修复MongoDB索引冲突")
    print("=" * 60)
    
    if fix_indexes():
        print("\n🎉 索引修复完成！")
    else:
        print("\n❌ 索引修复失败")

if __name__ == "__main__":
    main()
